// echo 服务端

#include "sock.h"
#include "rio.h"
#include "error.h"

#include <stdio.h>
#include <string.h>

#include <unistd.h>

#if defined(_WIN32)
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netdb.h>
#endif

void echo(int connfd);

int
main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <port>\n", argv[0]);
        return 1;
    }

    sock_init();

    const char *port = argv[1];

    int listenfd = sock_open_listenfd(port);

    int code;
    int connfd;
    struct sockaddr_storage clientaddr;
    socklen_t clientlen;

    char client_hostname[100];
    char client_port[10];
    for (;;) {
        clientlen = sizeof(clientaddr);
        connfd = accept(listenfd, (struct sockaddr*)&clientaddr, &clientlen);
        if (connfd < 0)
            unix_error("accept fail");
        if ((code = getnameinfo((struct sockaddr*)&clientaddr, clientlen, client_hostname, sizeof(client_hostname), client_port, sizeof(client_port), NI_NUMERICHOST)) != 0)
            gai_error(code, "getnameinfo fail");
        printf("Connection from %s:%s\n", client_hostname, client_port);
        
        echo(connfd);

        if (close(connfd) != 0)
            unix_error("close fail");
    }
    
    close(listenfd);
    sock_cleanup();
    return 0;
}

